package com.tiktok.config;

import com.tiktok.utils.JwtUtils;
import com.tiktok.utils.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * JWT认证拦截器
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class JwtAuthenticationInterceptor implements HandlerInterceptor {

    private final JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 获取Authorization头
        String authHeader = request.getHeader("Authorization");
        
        if (StringUtils.hasText(authHeader)) {
            String token = jwtUtils.extractToken(authHeader);
            
            if (token != null && jwtUtils.validateToken(token)) {
                // 从token中获取用户信息
                String username = jwtUtils.getUsernameFromToken(token);
                Long userId = jwtUtils.getUserIdFromToken(token);
                
                if (username != null && userId != null) {
                    // 设置用户上下文
                    UserContext.setUsername(username);
                    UserContext.setUserId(userId);
                    log.debug("用户认证成功：{}", username);
                }
            }
        }
        
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 清除用户上下文
        UserContext.clear();
    }
} 